package com.example.xm.controller;

import com.example.xm.web.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController

public class UploadController {
    @Value("${upload.src}")
    private String uploadSrc;
    @Autowired
    private MinioClient minioClient;
    @Value("${minio.bucketName}")
    private String bucketName;
    @Value("${server.port}")
    private String port;
    @RequestMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        System.out.println("aaaaaaaaaaaaaa"+uploadSrc);
//        原始名
        String originalFilename = file.getOriginalFilename();
        //后缀名
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //fileUrl
        String newFileName = UUID.randomUUID() + substring;
        //size
        long size = file.getSize();
        File file1 = new File(uploadSrc);
        if(!file1.exists()){
            file1.mkdirs();
        }
        File file2 = new File(file1, newFileName);
        file.transferTo(file2);
        System.out.println(newFileName);
//      FIleEntity entity=  new FIleEntity(null,originalFilename,newFileName, (double) size,substring, (short) 0);
//        fileService.add(entity);
        return Result.success("http://localhost:"+port+"/getImg?name="+newFileName);
    }
//    @RequestMapping("/upload")
//    public Result upload(MultipartFile file) throws IOException {
//        System.out.println("aaaaaaaaaaaaaa"+uploadSrc);
//        String originalFilename = file.getOriginalFilename();
//        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
//        String newFileName = UUID.randomUUID() + substring;
//        File file1 = new File(uploadSrc);
//        if(!file1.exists()){
//            file1.mkdirs();
//        }
//        File file2 = new File(file1, newFileName);
//        file.transferTo(file2);
//        System.out.println(newFileName);
//        return Result.success(newFileName);
//    }
    @RequestMapping("/getImg")
    public void getImg(String name, HttpServletResponse response) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(uploadSrc+"\\" + name);
        response.setContentType("image/jpeg");
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.copy(fileInputStream,outputStream);
        fileInputStream.close();
        outputStream.close();
    }
    @RequestMapping("/dowlon")
    public void dowlon(String name, HttpServletResponse response) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(uploadSrc+"\\" + name);
        response.setContentType("application/octet-stream");
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.copy(fileInputStream,outputStream);
        fileInputStream.close();
        outputStream.close();
    }
    @PostMapping("/minioUpload")
    public String minioUpload(@RequestParam("file") MultipartFile file) {
        try {
            // 检查存储桶是否存在
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());

            if (!bucketExists) {
                // 如果存储桶不存在，创建它
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(file.getOriginalFilename())
                    .stream(file.getInputStream(), file.getSize(), -1)  // 使用 InputStream 和文件大小
                    .contentType(file.getContentType())
                    .build();
            // 上传文件到指定的存储桶
            minioClient.putObject(putObjectArgs);

            return "File uploaded successfully: " + file.getOriginalFilename();
        } catch (Exception e) {
            e.printStackTrace();
            return "Error uploading file: " + e.getMessage();
        }
    }
}
